<template>
  <!-- 开药 -->
  <div>
    <the-dialog
      :cfg="drugCfg"
      width="80%"
      :loading="drugLoading"
      :need-close-modal="false"
      @closed="onClose()"
      @submited="onSubmitDrug"
    >
      <div slot="body" class="dialog-popup popup-drug__create">
        <div class="popup__frame drug__prescribing">
          <div class="frame__left">
            <!-- --------- 【中药】 --------- -->
            <el-form
              v-if="drugType == 1"
              class="x-form x-form--flex"
              ref="chineseForm"
              :model="chineseForm"
              :rules="chineseFormRule"
              label-position="left"
              label-width="90px"
              size="small"
            >
              <el-form-item label="用量" prop="detailsConsumption">
                <el-input-number
                  class="o-inp-number--full"
                  v-model="chineseForm.detailsConsumption"
                  placeholder="用量"
                  :controls="false"
                  :min="0"
                  :max="9999999"
                  :precision="1"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="用量单位" prop="detailsConsumptionUnit">
                <!-- 廉江医院-院内开药 -->
                <el-select
                  v-if="isLjDrug"
                  class="o-select--full"
                  v-model="chineseForm.detailsConsumptionUnit"
                  placeholder="请选择用量单位"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in hisUnitList"
                    :key="index"
                    :label="item.dictName"
                    :value="item.dictName"
                  ></el-option>
                </el-select>
                <!-- 其他医院 -->
                <el-select
                  v-else
                  class="o-select--full"
                  v-model="chineseForm.detailsConsumptionUnit"
                  placeholder="用量单位"
                  @change="changeCnUnit"
                  clearable
                >
                  <el-option
                    v-for="(o, idx) in drugDetail.consumptionList"
                    :key="idx"
                    :label="o"
                    :value="o"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                class="x-form__item--full"
                label="特殊用法"
                prop="detailsUsage"
              >
                <el-select
                  class="o-select--full"
                  v-model="chineseForm.detailsUsage"
                  placeholder="特殊用法"
                  clearable
                >
                  <el-option
                    v-for="(o, idx) in usageList"
                    :key="idx"
                    :label="o.usageName"
                    :value="o.usageName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>

            <!-- --------- 【西药】 --------- -->
            <el-form
              v-else
              class="x-form x-form--flex"
              ref="westernForm"
              :model="westernForm"
              :rules="westernFormRule"
              label-position="left"
              label-width="90px"
              size="small"
            >
              <el-form-item label="用量" prop="detailsConsumption">
                <el-input-number
                  class="o-inp-number--full"
                  v-model="westernForm.detailsConsumption"
                  placeholder="用量"
                  :controls="false"
                  :min="0"
                  :max="9999999"
                  :precision="1"
                  @keyup.native="changeWesternCount"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="用量单位" prop="detailsConsumptionUnit">
                <el-select
                  class="o-select--full"
                  v-model="westernForm.detailsConsumptionUnit"
                  placeholder="用量单位"
                  @change="changeWesternCount"
                >
                  <template v-if="isLjDrug">
                    <el-option
                      v-for="(o, idx) in hisUnitList"
                      :key="idx"
                      :label="o.dictName"
                      :value="o.dictName"
                    ></el-option>
                  </template>
                  <el-input
                    v-else-if="isZhDrug"
                    class="o-inp--full"
                    v-model.trim="westernForm.detailsConsumptionUnit"
                    placeholder="用量单位"
                    size="middle"
                    clearable
                  ></el-input>
                  <template v-else>
                    <el-option
                      v-for="(o, idx) in drugDetail.consumptionList"
                      :key="idx"
                      :label="o"
                      :value="o"
                    ></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item
                class="x-form__item--full"
                label="频次"
                prop="detailsFrequencyStr"
              >
                <el-select
                  v-if="isLjDrug"
                  class="o-select--full"
                  v-model="westernForm.detailsFrequencyName"
                  placeholder="频次"
                  @change="changeFrequency"
                  clearable
                >
                  <el-option
                    v-for="(o, idx) in frequencyList"
                    :key="idx"
                    :label="o.dictName"
                    :value="o.dictName"
                  ></el-option>
                </el-select>
                <el-select
                  v-else
                  class="o-select--full"
                  v-model="westernForm.detailsFrequencyName"
                  placeholder="频次"
                  @change="changeFrequency"
                  clearable
                >
                  <el-option
                    v-for="(o, idx) in frequencyList"
                    :key="idx"
                    :label="o.frequencyName"
                    :value="o.frequencyName"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                class="x-form__item--full"
                label="天数(天)"
                prop="detailsDay"
              >
                <div class="l-flex-1 l-flex">
                  <el-input-number
                    class="l-flex-1 o-inp-number--full"
                    v-model="westernForm.detailsDay"
                    placeholder="天数"
                    :controls="false"
                    :min="0"
                    :max="999"
                    :precision="0"
                    @change="changeWesternCount"
                  ></el-input-number>
                  <!-- <div class="prescribing__tips">(最多90天)</div> -->
                </div>
              </el-form-item>
              <el-form-item class="x-form__item--full" prop="detailsNum">
                <template slot="label">
                  <span>数量</span>
                  <span v-if="isZhDrug && drugDetail.unit"
                    >({{ drugDetail.unit }})</span
                  >
                  <span v-else-if="isLjDrug && drugDetail.packageUnitName"
                    >({{ drugDetail.packageUnitName }})</span
                  >
                  <span v-else-if="drugDetail.drugPackagingUnit"
                    >({{ drugDetail.drugPackagingUnit }})</span
                  >
                </template>
                <div class="l-flex-1 l-flex">
                  <el-input-number
                    class="o-inp-number--full l-flex-1"
                    v-model="westernForm.detailsNum"
                    placeholder="数量"
                    :controls="false"
                    :min="0"
                    :max="9999999"
                    :precision="0"
                    @keyup.native="changeWesternCount"
                  ></el-input-number>
                  <div class="prescribing__tips">
                    (根据用量、天数、频次计算)
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                class="x-form__item--full"
                label="用法"
                prop="detailsUsage"
              >
                <el-select
                  class="o-select--full"
                  v-model="westernForm.detailsUsage"
                  placeholder="用法"
                >
                  <template v-if="isLjDrug">
                    <el-option
                      v-for="(o, idx) in usageList"
                      :key="idx"
                      :label="o.dictName"
                      :value="o.dictName"
                    ></el-option>
                  </template>
                  <template v-else>
                    <el-option
                      v-for="(o, idx) in usageList"
                      :key="idx"
                      :label="o.usageName"
                      :value="o.usageName"
                    ></el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item
                class="x-form__item--full"
                label="用药嘱咐"
                prop="detailsEntrust"
              >
                <el-input
                  class="o-textarea--full"
                  type="textarea"
                  :row="5"
                  resize="none"
                  v-model.trim="westernForm.detailsEntrust"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="frame__right">
            <drug-info :key="drugDetail.id" :detail="drugDetail"></drug-info>
          </div>
        </div>
      </div>
    </the-dialog>
  </div>
</template>

<script>
import drugInfo from "./drug-detail";

export default {
  components: {
    drugInfo,
  },
  data() {
    return {
      isEdit: false,
      isLjDrug: false, // 属于廉江his院内来源
      isZhDrug: false, // 属于珠海360医保来源
      drugType: 1, // 1=中药，2=西药
      drugDetail: {},
      editData: {},
      drugCfg: {
        visible: false,
        title: "开药",
        confirmText: "保存",
      },
      drugLoading: false,
      frequencyList: [], // 频次选项
      frequencyItem: {}, // 当前选中的频次
      usageList: [], // 用法选项
      hisUnitList: [], // his 西药剂量单位
      hisCnUsageList: [], // his 用法用量单位

      westernForm: {
        detailsConsumption: undefined, //默认用量
        detailsConsumptionUnit: "", //用量单位（drugVolumeUnit）
        detailsDay: undefined, //天数
        detailsUsage: "", //用法
        detailsFrequency: "", // 频次id
        detailsFrequencyName: "", //频次名称(仅展示，无需提交)
        detailsFrequencyStr: "", //频次打印名称
        detailsEntrust: "", //嘱托
        detailsNum: undefined, // 数量
      },
      westernFormRule: {
        detailsConsumption: [
          { required: true, message: "用量不能为空", trigger: "blur" },
          { type: "number", min: 0.1, message: "请输入大于零的数值" },
        ],
        detailsConsumptionUnit: [
          { required: true, message: "用量单位不能为空", trigger: "change" },
        ],
        detailsFrequencyStr: [
          { required: true, message: "频次不能为空", trigger: "blur" },
        ],
        detailsDay: [
          { required: true, message: "天数不能为空", trigger: "blur" },
          { type: "number", min: 1, message: "请输入大于零的数值" },
        ],
        detailsNum: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { type: "number", min: 0.01, message: "请输入大于零的数值" },
        ],
        detailsUsage: [
          { required: true, message: "用法不能为空", trigger: "blur" },
        ],
      },
      chineseForm: {
        detailsConsumption: undefined,
        detailsConsumptionUnit: "",
        detailsUsage: "",
      },
      chineseFormRule: {
        detailsConsumption: [
          { required: true, message: "用量不能为空", trigger: "blur" },
          { type: "number", min: 0.01, message: "请输入大于零的数值" },
        ],
        detailsConsumptionUnit: [
          { required: true, message: "用量单位不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    drugDetail(newVal) {
      this.isLjDrug = !newVal.storeId || newVal.storeId === 0;
    },
  },
  methods: {
    /**
     * @param {object} data
     * isEdit 是否编辑
     * drugType 药品类型
     * editData 编辑的药品数据
     */
    onOpen(data = {}) {
      const { isEdit, drugType, drugId, editData } = data;
      this.isEdit = isEdit || false;
      this.drugType = drugType;
      this.editData = editData;

      this.isLjDrug =
        this.$global.platform("lj") &&
        (!editData.storeId || editData.storeId === 0);
      this.isZhDrug = this.$global.platform("zh") && data.paymentId == 2;

      this.drugCfg.visible = true;
      this.drugCfg.title = this.isEdit ? "编辑用药" : "新增用药";
      this.getDrugDetail(drugId);
      this.setFormdata(editData);
      this.getOptions();
    },
    onClose(flag = false) {
      this.drugCfg.visible = false;
      this.drugLoading = false;

      this.data = Object.assign({}, this.$options.data.call(this));
    },
    setFormdata(data = {}) {
      let formName = this.drugType == 1 ? "chineseForm" : "westernForm";
      // 药品默认值对应字段
      let fieldTemp = {
        chineseForm: {
          detailsConsumption: "usageNum", // 默认用量
          detailsConsumptionUnit: "useUnit", // 用量单位
          detailsUsage: "usageType", // 中药特殊用法
          drugPackagingUnit: "drugPackagingUnit",
        },
        westernForm: {
          detailsConsumption: "usageNum", // 默认用量
          detailsConsumptionUnit: "useUnit", //用量单位
          detailsDay: "drugMaxday", // 天数
          detailsUsage: "drugUsage", // 用法
          detailsEntrust: "enjoin", // 嘱托
          drugPackagingUnit: "drugPackagingUnit", // 包装单位
        },
      }[formName];

      if (this.isEdit) {
        /* --------- 编辑用药 --------- */
        for (let k in this[formName]) {
          if (
            [
              "detailsFrequencyStr",
              "detailsFrequency",
              "detailsFrequencyName",
            ].includes(k)
          ) {
            continue;
          } else if (["detailsConsumption", "detailsDay"].includes(k)) {
            this[formName][k] = data[k] ? Number(data[k]) : undefined;
          } else {
            this[formName][k] = data[k] || "";
          }
        }

        if (data.detailsFrequencyStr) {
          this.changeFrequency(data.detailsFrequencyStr);
        }
      } else {
        /* --------- 新增用药 --------- */
        if (this.isLjDrug) {
          /* --------- 廉江院内His --------- */
          if (this.drugType == 1) {
            this.chineseForm.detailsConsumption = undefined; //默认用量
            this.chineseForm.detailsConsumptionUnit =
              this.drugDetail.retailUnitName || ""; //用量单位（this.drugDetail.drugVolumeUnit）
            this.chineseForm.detailsUsage = ""; //中药特殊用法
          } else {
            this.westernForm.detailsConsumption =
              this.drugDetail.defaultDose || undefined; // 默认用量
            this.westernForm.detailsConsumptionUnit =
              this.drugDetail.doseUnitIame || ""; // 用量单位（this.drugDetail.drugVolumeUnit）
            this.westernForm.detailsDay = undefined; // 天数
            this.westernForm.detailsUsage =
              this.drugDetail.defaultUsageName || ""; // 用法
            this.westernForm.detailsFrequency =
              this.drugDetail.defaultFrequencyName || ""; // 频次id
            this.westernForm.detailsFrequencyStr =
              this.drugDetail.defaultFrequencyCode || ""; // 频次
            this.westernForm.detailsEntrust = ""; // 用药嘱咐

            this.changeFrequency();
          }
        } else {
          /* --------- 普通 or 廉江院外 --------- */
          for (let k in this[formName]) {
            switch (k) {
              case "detailsFrequency":
              case "detailsFrequencyName":
              case "detailsFrequencyStr":
                this.changeFrequency(); // 修改频率默认值
                break;
              case "detailsConsumption":
              case "detailsDay":
              case "detailsNum":
                this[formName][k] =
                  (fieldTemp[k] ? data[fieldTemp[k]] : data[k]) || undefined;
                break;
              default:
                this[formName][k] =
                  (fieldTemp[k] ? data[fieldTemp[k]] : data[k]) || "";
            }
          }
        }
      }
    },
    getDrugDetail(id) {
      this.drugLoading = true;
      let params = {};
      let api = "";

      if (this.isZhDrug) {
        params.id = id;
        api = "getDrugDetailByZh";
      } else if (this.isLjDrug) {
        params.drugType = this.drugType;
        params.drugCode = id;
        api = "getDrugDetailByLj";
      } else {
        params.id = id;
        api = "getDrugInfo";
      }

      this.$ajax[api](params)
        .then((res) => {
          this.drugLoading = false;
          this.drugDetail = res.data || {};
        })
        .catch((err) => {
          this.drugLoading = false;
          this.$util.message(err.msg);
        });
    },
    getOptions() {
      if (this.drugType == 2) {
        this.getFrequencyList();
      }

      if (this.isLjDrug) {
        this.getHisCnUsageList();
        this.getHisUnitList();
      }

      this.getUsageList();
    },
    // 获取频次数据
    getFrequencyList() {
      if (this.isLjDrug) {
        let params = {
          dictType: "60",
        };
        this.$ajax.getUsageOptionByLj(params).then((res) => {
          this.frequencyList = res.data || [];
        });
      } else {
        this.$ajax.getDrugFrequencyList().then((res) => {
          this.frequencyList = res.data.list || [];
        });
      }
    },
    // 获取用法数据
    getUsageList() {
      if (this.isLjDrug && this.drugType == 2) {
        this.$ajax.getUsageOptionByLj({ dictType: "51" }).then((res) => {
          this.usageList = res.data || [];
        });
      } else {
        /* --------- 西药用法or中药特殊用法 --------- */
        this.$ajax
          .getDrugUsageList({
            usageType: this.drugType == 1 ? 2 : 1,
          })
          .then((res) => {
            this.usageList = res.data.list || [];
          });
      }
    },
    // 【中药】获取his用法用量
    getHisCnUsageList() {
      this.$ajax.getUsageOptionByLj({ dictType: "103" }).then((res) => {
        this.hisCnUsageList = res.data || [];
      });
    },
    // 获取his药品剂量单位
    getHisUnitList() {
      this.$ajax.getUsageOptionByLj({ dictType: "20" }).then((res) => {
        this.hisUnitList = res.data || [];
      });
    },
    // 【西药】更新频次
    changeFrequency(query = "") {
      if (!query) {
        this.frequencyItem = {};
        this.westernForm.detailsFrequency = "";
        this.westernForm.detailsFrequencyName = "";
        this.westernForm.detailsFrequencyStr = "";
        return;
      }

      if (this.isLjDrug) {
        /* --------- 廉江His频次数据 --------- */
        let params = {
          dictType: "60",
          frequencyName: query || "",
        };
        this.$ajax.getUsageOptionByLj(params).then((res) => {
          if (res.data.list && res.data.length > 0) {
            this.frequencyItem = res.data[0];
          } else {
            this.frequencyItem = {
              dictName: query,
            };
          }

          this.westernForm.detailsFrequency = this.frequencyItem.dictCode || "";
          this.westernForm.detailsFrequencyName =
            this.frequencyItem.dictName || "";
          this.westernForm.detailsFrequencyStr =
            this.frequencyItem.dictName || "";
          this.changeWesternCount();
        });
      } else {
        let params = {
          frequencyName: query || "",
        };
        this.$ajax.getDrugFrequencyList(params).then((res) => {
          if (res.data.list && res.data.list.length > 0) {
            this.frequencyItem = res.data.list[0];
          } else {
            this.frequencyItem = {};
          }

          this.westernForm.detailsFrequency = this.frequencyItem.id || "";
          this.westernForm.detailsFrequencyName =
            this.frequencyItem.frequencyName || "";
          this.westernForm.detailsFrequencyStr =
            this.frequencyItem.frequencyPrintingName || "";
          this.changeWesternCount();
        });
      }
    },
    // 【西药】计算药品数量
    changeWesternCount() {
      if (this.drugDetail.drugType == 1 || this.isLjDrug || this.isZhDrug)
        return;

      let formValid =
        !!this.westernForm.detailsConsumption &&
        !!this.westernForm.detailsConsumptionUnit &&
        !!this.westernForm.detailsDay &&
        !!this.westernForm.detailsFrequencyStr; // 表单验证
      let frequencyValid =
        !!this.frequencyItem.frequencyNum &&
        !!this.frequencyItem.frequencyHoursNum; // 频次验证
      let drugValid =
        !!this.drugDetail.drugPackagingNum && !!this.drugDetail.goodsGuige; // 药品规格验证
      if (formValid && frequencyValid && drugValid) {
        /* 判断西药表单、频率、药品字段，满足计算条件，执行数量计算接口 */
        let result;
        let params = {
          bigPackaging: this.westernForm.goodsBigPacking, // 最大包装
          days: Number(this.westernForm.detailsDay), // 天数
          dosage: this.westernForm.detailsConsumption, // 用量
          usageUnit: this.westernForm.detailsConsumptionUnit, //  用药单位名称

          frequencyHoursNum: this.frequencyItem.frequencyHoursNum, // 每隔多少小时
          frequencyNum: this.frequencyItem.frequencyNum, // 频次

          drugSpecification: this.drugDetail.goodsGuige, // 药品规格,
          smallestPackaging: this.drugDetail.drugPackagingNum, // 最小包装
          mediumPackaging: this.drugDetail.goodsMediumPacking || "", // 中包装
          drugUnit: this.drugDetail.drugUnit || "", // 药品单位
          drugSmallestUnit: this.drugDetail.drugSmallestUnit || "", // 最小单位
          drugVolumeUnit: this.drugDetail.drugVolumeUnit || "", // 体积单位
        };

        this.$ajax
          .getTheCalculationFormula(params)
          .then((res) => {
            let num = Number(res.data.quantityOfMedication);
            this.westernForm.detailsNum = result = isNaN(num)
              ? undefined
              : Math.ceil(num);
          })
          .catch((err) => {
            this.$util.message(err.msg);
          });
      }
    },
    // 【中药】用量单位判断
    changeCnUnit() {
      if (
        this.drugDetail.goodsGuigeUnit &&
        this.chineseForm.detailsConsumptionUnit &&
        this.drugDetail.goodsGuigeUnit !=
          this.chineseForm.detailsConsumptionUnit
      ) {
        this.$message({
          message: "药品单位与药品规格单位不一致，请联系管理员处理后再重试",
          type: "error",
        });
      }
    },
    onSubmitDrug() {
      let formName = this.drugType == 1 ? "chineseForm" : "westernForm";
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.drugLoading = true;

          let temp = {
            drugSpecifications: this.drugDetail.drugSpecifications, // 规格
          };

          if (this.isLjDrug) {
            temp.storeId = 0;
            temp.storeName = "院内药房";
            temp.drugId = this.drugDetail.drugCode;
            temp.drugName = this.drugDetail.drugName;
            temp.drugPrice = this.drugDetail.retailPrice || "";
            temp.drugPackagingUnit = this.drugDetail.retailUnitName || ""; // 包装单位
          } else {
            if (this.isZhDrug) {
              temp.drugId = this.drugDetail.id;
              temp.drugName = this.drugDetail.name;
              temp.drugCommonCode = this.drugDetail.drugCommonCode || "";
              temp.drugSpecifications = this.drugDetail.norms || ""; // 规格
              temp.drugPackagingUnit =
                this.westernForm.detailsConsumptionUnit || "";
              temp.dosage = this.drugDetail.dosage || ""; // 剂型
            } else {
              temp.drugId = Number(this.drugDetail.id);
              temp.drugName = this.drugDetail.drugName;
            }

            temp.storeId = this.drugDetail.storeId;
            temp.storeName = this.drugDetail.storeName;
            temp.drugPrice = this.drugDetail.drugPrice;
            temp.drugPackagingUnit = this.drugDetail.drugPackagingUnit || "";
          }

          if (this.drugType == 1) {
            /* --------- 【中药】 --------- */
            for (let k in this.chineseForm) {
              temp[k] = this.chineseForm[k] || "";
            }

            if (this.isLjDrug) {
              temp.detailsNum = Number(this.chineseForm.detailsConsumption);
            } else {
              temp.detailsNum = Math.ceil(
                Number(this[formName].detailsConsumption) /
                  Number(this.drugDetail.goodsGuige)
              );
            }
          } else {
            /* --------- 【西药】 --------- */
            for (let k in this.westernForm) {
              temp[k] = this.westernForm[k] || "";
            }

            if (this.isLjDrug) {
              temp.drugCommonCode = this.drugDetail.drugCommonCode || ""; // 本位码
              temp.drugSpecifications = this.drugDetail.packageSpec || ""; // 规格
              temp.dosage = this.drugDetail.dosage || ""; // 剂型
            }
          }

          this.onClose(true);
          this.$emit("submited", this.isEdit, temp);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
